<?php

namespace app\controller;

use app\helper\CronHelper;
use app\helper\ProcessLockHelper;
use app\model\Crontab;
use app\model\CrontabLog;
use support\Request;

// https://www.agilebuilder.net/tools/app/cron,在线生成cron表达式
class CrontabController
{
  // 设定无需鉴权的函数
  protected $noNeedLogin = [];
  // 全局化
  private $cronHelper;
  // 初始化定义
  public function __construct()
  {
    $this->cronHelper = new CronHelper;
  }
  /**
   * 获取计划任务列表
   * @return \support\Response
   */
  public function index()
  {
    try {
      $result = $this->cronHelper->index(['page' => 1, "limit" => 10000]);
      return json(["code" => 200, "msg" => "获取成功", "data" => $result]);
    } catch (\Exception $e) {
      return json(["code" => 400, "msg" => $e->getMessage()]);
    }
  }

  /**
   * 添加计划任务
   * @param \support\Request $request
   * @return \support\Response
   */
  public function add(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['title', 'rule', 'parameter', 'remark', 'status']);
      $data['type'] = "1";
      $data['target'] = "php webman task:reseed";
      try {
        $this->cronHelper->add($data);
        return json(["code" => 200, "msg" => "计划任务添加成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 计划任务更新，参数ID
   * @param \support\Request $request
   * @return \support\Response
   */
  public function update(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id', 'title', 'rule', 'parameter', 'remark', 'status']);
      try {
        $this->cronHelper->update($data);
        return json(["code" => 200, "msg" => "计划任务修改成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 计划任务删除，参数ID
   * @param \support\Request $request
   * @return \support\Response
   */
  public function delete(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        $this->cronHelper->delete($data);
        return json(["code" => 200, "msg" => "计划任务删除成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 异步执行计划任务，通过后台指令，参考iyuu
   * @param \support\Request $request
   * @return \support\Response
   */
  public function run(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        $cmd = "php webman task:reseed " . $data['id'];
        $crontabTask = Crontab::find($data['id']);
        $crontabTask->running_times = $crontabTask->running_times + 1;
        $crontabTask->last_running_time = time();
        $crontabTask->save();
        if (DIRECTORY_SEPARATOR === '\\') {
          pclose(popen('start /B ' . $cmd, 'r'));
        } else {
          exec($cmd . ' &');
        }
        return json(["code" => 200, "msg" => "计划任务启动成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 计划任务重启，参数ID
   * @param \support\Request $request
   * @return \support\Response
   */
  public function reload(Request $request)
  {
    if ($request->method() == "POST") {
      try {
        $lock = new ProcessLockHelper(2);
        $lock->removeLock();
        $data = $request->only(['id']);
        $this->cronHelper->reload($data);
        return json(["code" => 200, "msg" => "计划任务重启"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 获取计划任务日志，参数ID
   * @param \support\Request $request
   * @return \support\Response
   */
  public function log(Request $request)
  {
    if ($request->method() == "POST") {
      try {
        $data = $request->only(['id']);
        $data = CrontabLog::where("crontab_id", $data['id'])->select();
        return json(["code" => 200, "msg" => "获取成功", "data" => $data]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

}
